package com.summary.richtext.controller;

import com.spire.license.LicenseProvider;
import com.summary.richtext.bean.PoundBean;
import com.summary.richtext.utils.excel.ImportExcel;
import com.summary.richtext.utils.word.Word2007Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.openxml4j.opc.internal.FileHelper;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.time.LocalDate;
import java.util.*;

@RestController
@RequestMapping("/pound")
public class EmcPoundController {

    @GetMapping(path = "/genFile")
    public Object genFile() throws Exception {
        String tmplPath = "D:\\guobd\\tmpl";
        File importExcelFile = new File(tmplPath+ "\\importExcel.xlsx");

        InputStream is = new BufferedInputStream(new FileInputStream(importExcelFile.getAbsolutePath()));
        ImportExcel importExcel = new ImportExcel(importExcelFile.getAbsolutePath() , is,1,0);
        List<PoundBean> dataList = importExcel.getDataList(PoundBean.class);

        int index = 0;
        List<String> pdfFilePathList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            FileInputStream fis = new FileInputStream(new File(tmplPath+ "\\pound.docx"));
            XWPFDocument document = new XWPFDocument(fis);
            for (int j = 1; j <= 3; j++) {
                if (i < dataList.size()) {
                    setDataToWord(document, dataList.get(i++), j);
                } else {
                    setDataToWord(document, new PoundBean(), j);
                }
            }
            i --;
            File outputFile = new File("D:\\guobd\\result\\wordFile\\file"+(index++)+".docx");
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                outputFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);
            document.write(fos);
            document.close();
            fis.close();
            fos.close();

            File tempPdfFile = wordToPdf(outputFile.getAbsolutePath());
            pdfFilePathList.add(tempPdfFile.getAbsolutePath());
        }

        String outputFile = "D:\\guobd\\过磅单.pdf";
        mergePdfFiles(pdfFilePathList, outputFile);
        return "文件处理完成！";
    }

    private static String getNotNull(String str, String def) {
        if (StringUtils.isEmpty(str)) {
            return def;
        }
        return str;
    }
    private static void setDataToWord(XWPFDocument document, PoundBean poundBean, int tableIndex) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("T"+tableIndex+"_EXT1", getNotNull(poundBean.getExt1(), ""));
        dataMap.put("T"+tableIndex+"_EXT2", getNotNull(poundBean.getExt2(), ""));
        dataMap.put("T"+tableIndex+"_EXT3", getNotNull(poundBean.getExt3(), ""));
        dataMap.put("T"+tableIndex+"_EXT4", getNotNull(poundBean.getExt4(), ""));
        dataMap.put("T"+tableIndex+"_EXT5", getNotNull(poundBean.getExt5(), ""));
        dataMap.put("T"+tableIndex+"_EXT6", getNotNull(poundBean.getExt6(), ""));
        dataMap.put("T"+tableIndex+"_EXT7", getNotNull(poundBean.getExt7(), ""));
        dataMap.put("T"+tableIndex+"_EXT8", getNotNull(poundBean.getExt8(), ""));
        dataMap.put("T"+tableIndex+"_EXT9", getNotNull(poundBean.getExt9(), ""));
        dataMap.put("T"+tableIndex+"_EXT10", getNotNull(poundBean.getExt10(), ""));
        dataMap.put("T"+tableIndex+"_EXT11", getNotNull(poundBean.getExt11(), ""));
        dataMap.put("T"+tableIndex+"_EXT12", getNotNull(poundBean.getExt12(), ""));
        dataMap.put("T"+tableIndex+"_EXT13", getNotNull(poundBean.getExt13(), ""));
        Word2007Utils.replaceAll(document, dataMap);
    }

    private static final String SPIRE_LICENSE_KEY = "WwEA5eVo9kRbzFKa+KIfUNXyrFDTreXKdr/8DDqMyYD+2lL7/+1D+ayIsEtdL8W1RKdxAT/z8n/XE9EW1ahlx6z9pmQ8tV6u7MTDmVOBZAxn1"
            + "0B0oHhYYCsG5qbfJ/72FBzinyKF3aY8ERAqqPxIhAKblt3sQB19CXBl0e32FNvdVVTB/3105zOfYTYB0UovDFFTZfN8zbaebMhoyoFLvNpC1cHdt0P89hsJeENYI"
            + "L2NknIZYjgbjcZuMGC9jjhkwclsaucpbUpvccXKmd1Y3mmIs75lGMmJ9M9QLIZTiJv2ypPx1HNmBcjE/eEcGD+vHYOqC5pPcgniTs6ioLhZc2KX8TH66BpODOo2C"
            + "1UJTwht3kL/3sZ0kkuFNKn8RnXUyvXmf12l+3lL9UbItHq3HiaFVVpXWYvuICWp6TPQAXOrSOScmpRggoe7UE8oJD1USei9JQsK8zTQpz8Ur/ahrt0e5eIW/iqP6"
            + "xULuJxoriBZZWKjTlXZIYNPNsJnIlQKarMNYkWT3a6BLgRGBXfwdmA4P9uKrDwwnBklkEnJ+ayFKyLNubzlOA1Wn7/np/3eOEBKY4yY9w6XsWY3lL7qFJOXle1F4"
            + "xcn5m+QdAePQZVycw6JrGs2S7wkFn3dF+6UtDYuK9vnsWFoKdBdO2B12wQXt1jniL3p485Kc/C5UjVFdWoud0JPypoet6PoG9X0VdSlVa6lDXFGRXojSnY1gcM7f"
            + "KNRWGM0L8T0aErvbD6lj10Y7+jxv6UhFJ1zP+opmPjPVM8gUagc1pAZtveyzBLOgWCrlSE2Y1FhyUbBdgFQi7nyOPAGW/vhF0KrDDFNFIGvCzbt6aM7+gyWymHtU"
            + "QwSz1P9Oe+4yz9VogwhFLl3h7/L8DnU3G/wT9UOQTetzNmNgqw50KEouTMhwDjcB4cTMuWigeUcTjy8F+RYEpi5CG5xjCoYEWKSiBEnfgvgH9EGPRDqBXEVe3kD2"
            + "L6xAg7J0yAG+9pjEFsYHedofyOxP7SPErfYcHCN8yEQy/pMn05VRboGjaFWl2NrEf/o12lUSqNFdR1oVUnVabRESbrruCd05esez5WIrUEO6pCngZwQ+mO+B3MvS"
            + "Sj0tbtN0ivzDlNNVNw5ZqK6oebCm3TPQhe8PWtvBp029KM1PuhiB8uFm1epHOpSh6+zrnMFDzfze0BJZ8ah63Jc207PZA4DSU6u5I+1MHg0Bb6Ch3kj7aqDouqUG"
            + "XRchk7nYp5sGSq2bVpGE1hE2PSWK+RdpwvAlwsOotUY5maGQ+H0c1d0dYgeXwUhgWqOns9Ye4tgZIms36BWGY9/qfkJxl61RgeQqEhODZQ3JFZi9M9J9RgRYJCMr"
            + "nDHVc0UO96KYVG1Ym+fpZMljgotwbBRu3X825jAydEVw4IJM2uxQhHVQzsW/JH/jeXd2HNCwUtutuVslkWGgvOS8P4gansqsNrEqhkaeOl7gDhTKaNJSTd98KnfC"
            + "ra9NbLVgse0H3g9kOqsMI1WZk4IyrA93DzIPPdY7BhcQZGMpmzDc7Q5s6VSIrgJ";

    public static File wordToPdf(String pacth) {
        File file = new File(pacth.substring(0, pacth.lastIndexOf(".")) + ".pdf");
        LicenseProvider.setLicenseKey(SPIRE_LICENSE_KEY);
        com.spire.doc.Document doc = new com.spire.doc.Document();
        doc.loadFromFile(pacth);
        doc.saveToFile(file.getAbsolutePath());
        return file;
    }

    public static void mergePdfFiles(List<String> inputPaths, String outputPath) throws IOException {
        PDFMergerUtility pdfMerger = new PDFMergerUtility();
        // 添加所有需要合并的PDF文件
        for (String path : inputPaths) {
            pdfMerger.addSource(new File(path));
        }
        // 设置输出文件路径
        pdfMerger.setDestinationFileName(outputPath);

        // 执行合并操作
        pdfMerger.mergeDocuments(null);
    }

}
